package com.keyboardr.gamerater;

import java.io.File;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.keyboardr.gamerater.filechooser.FileChooser;

public class GroupsFragment extends ListFragment implements
		OnItemLongClickListener {

	private static final int REQUEST_EXPORT = 100;
	private static final int REQUEST_IMPORT = 101;
	private ActionMode mCurrentActionMode;
	private Group exportingGroup;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setHasOptionsMenu(true);
	}

	@Override
	public void onStart() {
		super.onStart();
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		getListView().setOnItemLongClickListener(this);

		if (RaterActivity.isHolo) {
			registerForContextMenu(getListView());
			setListAdapter(new ArrayAdapter<Group>(getActivity(),
					android.R.layout.simple_list_item_activated_1,
					((GroupContainer) getActivity()).getGroupList()));
		} else {
			setListAdapter(new ArrayAdapter<Group>(getActivity(),
					android.R.layout.simple_list_item_1,
					((GroupContainer) getActivity()).getGroupList()));
		}
		updateGroupSelection();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		((GroupContainer) getActivity()).selectGroup(position);
	}

	public void updateGroupSelection() {
		getListView().setItemChecked(
				((GroupContainer) getActivity()).getSelectedGroupPosition(),
				true);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.groups, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.newGroup:

			new NewGroupDialogFragment().show(getFragmentManager(), null);
			return true;
		case R.id.importGroup:
			importGroup();
			return true;
		}
		return false;
	}

	private void importGroup() {
		Intent fileChooserIntent = new Intent(getActivity(), FileChooser.class);
		fileChooserIntent.putExtra(FileChooser.EXTRA_ALLOW_CREATE, false);
		startActivityForResult(fileChooserIntent, REQUEST_IMPORT);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		if (RaterActivity.isHolo) {
			final int pos = position;
			if (mCurrentActionMode != null) {
				return false;
			}

			mCurrentActionMode = getActivity().startActionMode(
					new ActionMode.Callback() {

						@Override
						public boolean onCreateActionMode(ActionMode mode,
								Menu menu) {
							mode.setTitle(((GroupContainer) getActivity())
									.getGroupList().get(pos).toString());
							MenuInflater inflater = mode.getMenuInflater();
							inflater.inflate(R.menu.group_context, menu);
							return true;
						}

						@Override
						public boolean onPrepareActionMode(
								ActionMode paramActionMode, Menu paramMenu) {
							return false;
						}

						@Override
						public void onDestroyActionMode(
								ActionMode paramActionMode) {
							mCurrentActionMode = null;
						}

						@Override
						public boolean onActionItemClicked(ActionMode mode,
								MenuItem paramItem) {
							switch (paramItem.getItemId()) {
							case R.id.deleteGroup:
								showDeleteDialog(pos);
								mode.finish();
								return true;
							case R.id.selectGroup:
								((GroupContainer) getActivity())
										.selectGroup(pos);
								mode.finish();
								return true;
							case R.id.exportGroup:
								mode.finish();
								return exportGroup(pos);
							}
							return false;
						}
					});
			return true;
		} else {
			final int pos = position;
			final QuickAction quickAction = new QuickAction(view);

			ActionItem deleteAction = new ActionItem(getResources()
					.getDrawable(android.R.drawable.ic_menu_delete));
			deleteAction.setTitle(getResources()
					.getString(R.string.deleteGroup));
			deleteAction.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					showDeleteDialog(pos);
					quickAction.dismiss();
				}
			});
			quickAction.addActionItem(deleteAction);

			ActionItem selectAction = new ActionItem(getResources()
					.getDrawable(android.R.drawable.ic_menu_set_as));
			selectAction.setTitle(getResources()
					.getString(R.string.selectGroup));
			selectAction.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					quickAction.dismiss();
					((GroupContainer) getActivity()).selectGroup(pos);
				}
			});
			quickAction.addActionItem(selectAction);

			ActionItem exportAction = new ActionItem(getResources()
					.getDrawable(android.R.drawable.ic_menu_save));
			exportAction.setTitle(getResources()
					.getString(R.string.exportGroup));
			exportAction.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					quickAction.dismiss();
					exportGroup(pos);
				}
			});
			quickAction.addActionItem(exportAction);

			quickAction.show();
			return true;
		}
	}

	@Override
	public boolean onContextItemSelected(final MenuItem item) {
		final int pos = ((AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo()).position;
		switch (item.getItemId()) {
		case R.id.deleteGroup:
			showDeleteDialog(pos);
			return true;
		case R.id.selectGroup:
			((GroupContainer) getActivity())
					.selectGroup(((AdapterView.AdapterContextMenuInfo) item
							.getMenuInfo()).position);
			return true;
		case R.id.exportGroup:
			return exportGroup(pos);
		}
		return false;
	}

	private boolean exportGroup(int pos) {
		exportingGroup = ((GroupContainer) getActivity()).getGroupList().get(
				pos);
		Intent fileChooserIntent = new Intent(getActivity(), FileChooser.class);
		fileChooserIntent.putExtra(FileChooser.EXTRA_ALLOW_CREATE, true);
		startActivityForResult(fileChooserIntent, REQUEST_EXPORT);
		return true;
	}

	public void showDeleteDialog(final int pos) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage("Are you sure you want to delete this group?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								((GroupContainer) getActivity())
										.removeGroup(pos);
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		Dialog deleter = builder.create();
		deleter.show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_EXPORT:
			if (resultCode == Activity.RESULT_OK) {
				SaveFileTask sft = new SaveFileTask(
						data.getStringExtra(FileChooser.EXTRA_RESULT));
				sft.execute(exportingGroup);
			}
			exportingGroup = null;
			break;
		case REQUEST_IMPORT:
			if (resultCode == Activity.RESULT_OK) {
				LoadFileTask lft = new LoadFileTask(
						(GroupContainer) getActivity());
				File file = new File(
						data.getStringExtra(FileChooser.EXTRA_RESULT));
				lft.execute(file);
			}
			break;
		}
	}
}
